package com.artifex.mupdf.viewer;

import static android.widget.Toast.LENGTH_LONG;
import static com.artifex.mupdf.viewer.SettingsItem.TYPE.PAGE;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.MenuProvider;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.artifex.mupdf.fitz.Quad;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.mlkit.samples.nl.translate.AppExecutor;
import com.google.mlkit.samples.nl.translate.java.MainActivity;

import java.util.ArrayList;
import java.util.Locale;

public class TTSDocumentActivity extends AppCompatActivity implements MenuProvider, TTSService.TTSCallback {
    private final String TAG = "TTSDocumentActivity";
    private SharedPreferences prefs;

    /* The core rendering instance */
    enum TopBarMode {Main, Search, More}

    private final int OUTLINE_REQUEST = 0;
    private TTSDocument core;
    private ReaderView mDocView;
    private boolean mButtonsVisible = true;
    private EditText mPasswordView;
    private TextView mPageNumberView;
    private ViewAnimator mTopBarSwitcher;
    private TopBarMode mTopBarMode = TopBarMode.Main;
    private ImageButton mSearchBack;
    private ImageButton mSearchFwd;
    private EditText mSearchText;
    private SearchTask mSearchTask;
    private AlertDialog.Builder mAlertBuilder;
    private boolean mLinkHighlight = false;
    private ArrayList<OutlineActivity.Item> mFlatOutline;

    protected int mDisplayDPI;
    private int mLayoutEM = 10;
    private int mLayoutW = 312;
    private int mLayoutH = 504;
    protected PopupMenu mLayoutPopupMenu;
    TTSService ttsService;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        ViewCompat.setOnApplyWindowInsetsListener(getWindow().getDecorView(), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        setContentView(R.layout.tts_document_activity);

        prefs = getSharedPreferences(TTSDocument.base64(getIntent().getDataString()), Context.MODE_PRIVATE);
        super.onCreate(savedInstanceState);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mDisplayDPI = metrics.densityDpi;

        mAlertBuilder = new AlertDialog.Builder(this);

        MaterialToolbar toolbar = findViewById(R.id.toolbar);
        toolbar.addMenuProvider(this);
    }

    public void requestPassword() {
        mPasswordView = new EditText(this);
        mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
        mPasswordView.setTransformationMethod(new PasswordTransformationMethod());

        AlertDialog alert = mAlertBuilder.create();
        alert.setTitle(R.string.enter_password);
        alert.setView(mPasswordView);
        alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.okay),
                new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    public void onClick(DialogInterface dialog, int which) {
                        if (core.authenticatePassword(mPasswordView.getText().toString())) {
                            createUI();
                        } else {
                            requestPassword();
                        }
                    }
                });
        alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                (dialog, which) -> finish());
        alert.show();
    }

    public void relayoutDocument() {
        AppExecutor.obtain().submit(() -> {
            core.layout(mDocView.mCurrent, mLayoutW, mLayoutH, mLayoutEM);
            runOnUiThread(() -> {
                mFlatOutline = null;
                mDocView.mHistory.clear();
                mDocView.refresh();
            });
        });
    }

    ReaderView.Callback newReaderCallback() {
        return new ReaderView.Callback() {
            @Override
            public void onMoveToChild(int i) {
                if (core == null)
                    return;
                mPageNumberView.setText(String.format(Locale.ROOT, "%d / %d", i + 1, core.doc.countPages()));
            }

            @Override
            public void onTapMainDocArea() {
                if (!mButtonsVisible) {
                    showButtons();
                } else {
                    if (mTopBarMode == TopBarMode.Main)
                        hideButtons();
                }
            }

            @Override
            public void onDocMotion() {
                hideButtons();
            }

            @Override
            public void onSizeChanged(int w, int h, int preW, int preH) {
                Log.d(TAG, "onSizeChanged: " + w + ", " + h + " From: " + preW + ", " + preH);
                if (core == null)
                    return;
                if (core.doc.isReflowable()) {
                    mLayoutW = w * 72 / mDisplayDPI;
                    mLayoutH = h * 72 / mDisplayDPI;
                    relayoutDocument();
                } else {
                    mDocView.refresh();
                }
            }
        };
    }

    PageAdapter pageAdapter;

    public void createUI() {
        if (core == null) {
            return;
        } else if (mDocView != null) {
            pageAdapter.update(core);
            mSearchTask.update(core);
            mDocView.post(() -> mDocView.setDisplayedViewIndex(prefs.getInt(PAGE.name(), 0)));
            return;
        }

        mDocView = findViewById(R.id.reader);
        ReaderView.Callback readerCallback = newReaderCallback();
        mDocView.setCallback(readerCallback);
        pageAdapter = new PageAdapter(this, core);
        mDocView.setAdapter(pageAdapter);
        readerCallback.onSizeChanged(mDocView.getWidth(), mDocView.getHeight(), 0, 0);

        mSearchTask = new SearchTask(this, core) {
            @Override
            protected void onTextFound(SearchTaskResult result) {
                SearchTaskResult.set(result);
                // Ask the ReaderView to move to the resulting page
                mDocView.setDisplayedViewIndex(result.pageNumber);
                // Make the ReaderView act on the change to SearchTaskResult
                // via overridden onChildSetup method.
                mDocView.reSetupChildren();
            }
        };

        // Make the buttons overlay, and store all its
        // controls in variables
        mPageNumberView = findViewById(R.id.pageNumber);
        mTopBarSwitcher = findViewById(R.id.switcher);
        mSearchBack = findViewById(R.id.searchBack);
        mSearchFwd = findViewById(R.id.searchForward);
        ImageButton mSearchClose = findViewById(R.id.searchClose);
        mSearchText = findViewById(R.id.searchText);
        mPageNumberView.setOnClickListener(v -> showNumberInputDialog());

        // Activate the search-preparing button
        mSearchClose.setOnClickListener(v -> searchModeOff());

        // Search invoking buttons are disabled while there is no text specified
        mSearchBack.setEnabled(false);
        mSearchFwd.setEnabled(false);
        mSearchBack.setColorFilter(Color.argb(255, 128, 128, 128));
        mSearchFwd.setColorFilter(Color.argb(255, 128, 128, 128));

        // React to interaction with the text widget
        mSearchText.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                boolean haveText = !s.toString().isEmpty();
                setButtonEnabled(mSearchBack, haveText);
                setButtonEnabled(mSearchFwd, haveText);

                // Remove any previous search results
                if (SearchTaskResult.get() != null && !mSearchText.getText().toString().equals(SearchTaskResult.get().txt)) {
                    SearchTaskResult.set(null);
                    mDocView.reSetupChildren();
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }
        });

        //React to Done button on keyboard
        mSearchText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE)
                search(1);
            return false;
        });

        mSearchText.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
                search(1);
            return false;
        });

        // Activate search invoking buttons
        mSearchBack.setOnClickListener(v -> search(-1));
        mSearchFwd.setOnClickListener(v -> search(1));

        mDocView.post(() -> mDocView.setDisplayedViewIndex(prefs.getInt(PAGE.name(), 0)));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OUTLINE_REQUEST) {
            if (resultCode >= RESULT_FIRST_USER && mDocView != null) {
                mDocView.pushHistory();
                mDocView.setDisplayedViewIndex(resultCode - RESULT_FIRST_USER);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        if (mDocView != null) {
            // Store current page in the prefs against the file name,
            // so that we can pick it up each time the file is loaded
            // Other info is needed only for screen-orientation change,
            // so it can go in the bundle
            prefs.edit().putInt(PAGE.name(), mDocView.getDisplayedViewIndex()).apply();
        }

        if (!mButtonsVisible)
            outState.putBoolean("ButtonsHidden", true);

        if (mTopBarMode == TopBarMode.Search)
            outState.putBoolean("SearchMode", true);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onPause() {
        super.onPause();

        if (mSearchTask != null)
            mSearchTask.stop();

        if (mDocView != null) {
            prefs.edit().putInt(PAGE.name(), mDocView.getDisplayedViewIndex()).apply();
        }

        // Service continues running independently
        if (ttsService != null) {
            Log.d("TTSDocumentActivity", "unbindService");
            // Don't stop the service, just unbind
            ttsService.setCallback(null);
            unbindService(ttsConnection);
            ttsService = null;
        }
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        if (mDocView != null) {
            mDocView.applyToChildren(view -> ((PageView) view).releaseBitmaps());
        }
        core = null;
        super.onDestroy();
    }

    private void setButtonEnabled(ImageButton button, boolean enabled) {
        button.setEnabled(enabled);
        button.setColorFilter(enabled ? Color.argb(255, 255, 255, 255) : Color.argb(255, 128, 128, 128));
    }

    private void setLinkHighlight(boolean highlight) {
        mLinkHighlight = highlight;
        // Inform pages of the change.
        mDocView.setLinksEnabled(highlight);
    }

    private void showButtons() {
        if (core == null)
            return;
        if (!mButtonsVisible) {
            mButtonsVisible = true;
            // Update page number text and slider
            int index = mDocView.getDisplayedViewIndex();
            updatePageNumView(index);
            if (mTopBarMode == TopBarMode.Search) {
                mSearchText.requestFocus();
                showKeyboard();
            }

            Animation anim = slideInAnim();
            mTopBarSwitcher.startAnimation(anim);
        }
    }

    @NonNull
    private Animation slideInAnim() {
        Animation anim = new TranslateAnimation(0, 0, -mTopBarSwitcher.getHeight(), 0);
        anim.setDuration(200);
        anim.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationStart(Animation animation) {
                mTopBarSwitcher.setVisibility(View.VISIBLE);
                mPageNumberView.setVisibility(View.VISIBLE);
            }

            public void onAnimationRepeat(Animation animation) {
            }

            public void onAnimationEnd(Animation animation) {
            }
        });
        return anim;
    }

    private void hideButtons() {
        if (mButtonsVisible) {
            mButtonsVisible = false;
            hideKeyboard();

            Animation anim = new TranslateAnimation(0, 0, 0, -mTopBarSwitcher.getHeight());
            anim.setDuration(200);
            anim.setAnimationListener(new Animation.AnimationListener() {
                public void onAnimationStart(Animation animation) {
                }

                public void onAnimationRepeat(Animation animation) {
                }

                public void onAnimationEnd(Animation animation) {
                    mTopBarSwitcher.setVisibility(View.INVISIBLE);
                    mPageNumberView.setVisibility(View.INVISIBLE);
                }
            });
            mTopBarSwitcher.startAnimation(anim);
        }
    }

    private void searchModeOn() {
        if (mTopBarMode != TopBarMode.Search) {
            mTopBarMode = TopBarMode.Search;
            //Focus on EditTextWidget
            mSearchText.requestFocus();
            showKeyboard();
            mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
        }
    }

    private void searchModeOff() {
        if (mTopBarMode == TopBarMode.Search) {
            mTopBarMode = TopBarMode.Main;
            hideKeyboard();
            mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
            SearchTaskResult.set(null);
            // Make the ReaderView act on the change to mSearchTaskResult
            // via overridden onChildSetup method.
            mDocView.reSetupChildren();
        }
    }

    private void updatePageNumView(int index) {
        if (core == null)
            return;
        mPageNumberView.setText(String.format(Locale.ROOT, "%d / %d", index + 1, core.doc.countPages()));
    }

    private void showKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null)
            imm.showSoftInput(mSearchText, 0);
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null)
            imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
    }

    private void search(int direction) {
        hideKeyboard();
        int displayPage = mDocView.getDisplayedViewIndex();
        SearchTaskResult r = SearchTaskResult.get();
        int searchPage = r != null ? r.pageNumber : -1;
        mSearchTask.go(mSearchText.getText().toString(), direction, displayPage, searchPage);
    }

    @Override
    public boolean onSearchRequested() {
        if (mButtonsVisible && mTopBarMode == TopBarMode.Search) {
            hideButtons();
        } else {
            showButtons();
            searchModeOn();
        }
        return super.onSearchRequested();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    private final ServiceConnection ttsConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("TTSDocumentActivity", "onServiceConnected");
            TTSService.TTSBinder binder = (TTSService.TTSBinder) service;
            ttsService = binder.getService();
            ttsService.setCallback(TTSDocumentActivity.this);
            ttsService.prepareDoc(getIntent().getData());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            ttsService = null;
        }
    };

    // Modified TTSCallback

    @Override
    public void onSegmentStart(Quad[][] boxes) {
        // Highlight the text being spoken
        runOnUiThread(() -> mDocView.highlight(boxes));
    }

    @Override
    public void onSegmentDone(int page, int segmentIndex) {
    }

    @Override
    public void onPageChanged(int newPage) {
        runOnUiThread(() -> mDocView.setDisplayedViewIndex(newPage));
    }

    @Override
    public void onTTSInitialized(boolean success) {
        runOnUiThread(() -> {
            if (success) {
                Toast.makeText(TTSDocumentActivity.this, "TTS initialized", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TTSDocumentActivity.this, "TTS initialization failed", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onTTSStopped() {
    }

    @Override
    public void onError(String message) {
        runOnUiThread(() -> Toast.makeText(TTSDocumentActivity.this, "TTS Error: " + message, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onDocCreated(TTSDocument document) {
        if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
            Uri uri = getIntent().getData();

            if (uri == null) {
                showCannotOpenDialog();
                return;
            }
            Log.i(TAG, "OPEN URI " + uri);
            core = document;

            SearchTaskResult.set(null);

            if (core == null) {
                AlertDialog alert = mAlertBuilder.create();
                alert.setTitle(R.string.cannot_open_document);
                alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dismiss),
                        (dialog, which) -> finish());
                alert.setOnCancelListener(dialog -> finish());
                alert.show();
                return;
            }
            if (core.doc.countPages() == 0) {
                Toast.makeText(TTSDocumentActivity.this, "0 page", LENGTH_LONG).show();
                core = null;
                return;
            }
            if (core.needsPassword()) {
                requestPassword();
            }
            createUI();
        } else {
            Toast.makeText(TTSDocumentActivity.this, "No data received", LENGTH_LONG).show();
        }
    }

    @Override
    public void onQuit() {
        runOnUiThread(this::finishAffinity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Bind to service for callbacks
        if (ttsService == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.d("TTSDocumentActivity", "startForegroundService before bind it to make it sticky which means the service will not be destroyed even unbind");
                startForegroundService(new Intent(TTSDocumentActivity.this, TTSService.class));
            }
            Log.d("TTSDocumentActivity", "try to bindService");
            Intent serviceIntent = new Intent(TTSDocumentActivity.this, TTSService.class);
            serviceIntent.setData(getIntent().getData());
            bindService(serviceIntent, ttsConnection, Context.BIND_AUTO_CREATE);
        }
        if (ttsService != null) {
            ttsService.setCallback(TTSDocumentActivity.this);
            // Update UI with current reading position
            if (ttsService.isSpeaking()) {
                int currentPage = ttsService.getCurrentPage();
                mDocView.setDisplayedViewIndex(currentPage);
            }
        }
        if (core != null && !core.destroyed()) {
            mDocView.setDisplayedViewIndex(prefs.getInt(PAGE.name(), 0));
        }
    }

    // In your Activity or Fragment
    private void showNumberInputDialog() {
        // Inflate the custom layout
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_number_input, null);

        // Find views
        EditText etNumber = dialogView.findViewById(R.id.etNumberInput);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);
        Button btnOk = dialogView.findViewById(R.id.btnOk);

        // Create the dialog
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setCancelable(false)
                .create();

        // Set click listeners
        btnCancel.setOnClickListener(v -> dialog.dismiss());

        btnOk.setOnClickListener(v -> {
            String input = etNumber.getText().toString().trim();
            if (!input.isEmpty()) {
                try {
                    int number = Integer.parseInt(input);
                    dialog.dismiss();
                    // Do something with the number
                    if (number > core.doc.countPages()) {
                        etNumber.setError("Out of bound");
                        return;
                    }
                    mDocView.setDisplayedViewIndex(number - 1);

                } catch (NumberFormatException e) {
                    etNumber.setError("Please enter a valid number");
                }
            } else {
                etNumber.setError("Please enter a number");
            }
        });

        // Show keyboard automatically
        etNumber.setOnFocusChangeListener((v, hasFocus) -> {
            Window window = dialog.getWindow();
            if (hasFocus && window != null) {
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        });

        // Show the dialog
        dialog.show();
    }


    private void showCannotOpenDialog() {
        Resources res = getResources();
        AlertDialog alert = mAlertBuilder.create();
        setTitle(String.format(Locale.ROOT, res.getString(R.string.cannot_open_document_Reason), "No document uri to open"));
        alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dismiss),
                (dialog, which) -> finish());
        alert.show();
    }

    void onClickLayout() {
        if (core.doc.isReflowable()) {
            if (mLayoutPopupMenu == null) {
                mLayoutPopupMenu = new PopupMenu(this, findViewById(R.id.toolbar));
                mLayoutPopupMenu.getMenuInflater().inflate(R.menu.layout_menu, mLayoutPopupMenu.getMenu());
                mLayoutPopupMenu.setOnMenuItemClickListener(item -> {
                    float oldLayoutEM = mLayoutEM;
                    int id = item.getItemId();
                    if (id == R.id.action_layout_6pt) mLayoutEM = 6;
                    else if (id == R.id.action_layout_7pt) mLayoutEM = 7;
                    else if (id == R.id.action_layout_8pt) mLayoutEM = 8;
                    else if (id == R.id.action_layout_9pt) mLayoutEM = 9;
                    else if (id == R.id.action_layout_10pt) mLayoutEM = 10;
                    else if (id == R.id.action_layout_11pt) mLayoutEM = 11;
                    else if (id == R.id.action_layout_12pt) mLayoutEM = 12;
                    else if (id == R.id.action_layout_13pt) mLayoutEM = 13;
                    else if (id == R.id.action_layout_14pt) mLayoutEM = 14;
                    else if (id == R.id.action_layout_15pt) mLayoutEM = 15;
                    else if (id == R.id.action_layout_16pt) mLayoutEM = 16;
                    if (oldLayoutEM != mLayoutEM)
                        relayoutDocument();
                    return true;
                });
            }
            mLayoutPopupMenu.show();
        }
    }

    @Override
    public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
        menuInflater.inflate(R.menu.document_menu, menu);
    }

    @Override
    public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.action_link) {
            setLinkHighlight(!mLinkHighlight);
        } else if (menuItem.getItemId() == R.id.action_timer) {
            Intent settingIntent = new Intent(TTSDocumentActivity.this, TimerSettingsActivity.class);
            settingIntent.setData(getIntent().getData());
            startActivity(settingIntent);
        } else if (menuItem.getItemId() == R.id.action_regex) {
            if (ttsService != null) {
                ttsService.stopReading();
            }
            Intent settingIntent = new Intent(TTSDocumentActivity.this, PatternManagerActivity.class);
            settingIntent.setData(getIntent().getData());
            startActivity(settingIntent);
        } else if (menuItem.getItemId() == R.id.action_outline) {
            if (core.hasOutline()) {
                if (mFlatOutline == null)
                    mFlatOutline = core.getOutline();
                if (mFlatOutline != null) {
                    Intent intent = new Intent(TTSDocumentActivity.this, OutlineActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("POSITION", mDocView.getDisplayedViewIndex());
                    bundle.putSerializable("OUTLINE", mFlatOutline);
                    intent.putExtra("PALLETBUNDLE", Pallet.sendBundle(bundle));
                    startActivityForResult(intent, OUTLINE_REQUEST);
                }
            }
        } else if (menuItem.getItemId() == R.id.action_layout) {
            onClickLayout();
        } else if (menuItem.getItemId() == R.id.action_search) {
            searchModeOn();
        } else if (menuItem.getItemId() == R.id.action_translate) {
            startActivity(new Intent(TTSDocumentActivity.this, MainActivity.class));
        } else if (menuItem.getItemId() == R.id.action_stop) {
            if (ttsService != null) {
                ttsService.stopReading();
            }
        } else if (menuItem.getItemId() == R.id.action_pause) {
            if (ttsService != null) {
                ttsService.pauseReading();
            }
        } else if (menuItem.getItemId() == R.id.action_play) {
            if (ttsService != null) {
                ttsService.startReading(mDocView.getDisplayedViewIndex());
            }
        } else if (menuItem.getItemId() == R.id.action_setting) {
            if (ttsService != null) {
                ttsService.stopReading();
            }
            Intent settingIntent = new Intent(TTSDocumentActivity.this, TTSSettingsActivity.class);
            settingIntent.setData(getIntent().getData());
            startActivity(settingIntent);
        } else if (menuItem.getItemId() == R.id.action_continue) {
            mDocView.setDisplayedViewIndex(prefs.getInt(PAGE.name(), 0));
        }
        return false;
    }
}